package com.lx.javasunmmrize.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description 使用买票案例测试lock
 * @Author lx
 * @Date 2021/3/1 23:33
 **/
public class LockTest implements Runnable {
    //定义票
    private int tockit = 10;

    //创建lock对象(保证锁是私有的且唯一)
    private final ReentrantLock lock = new ReentrantLock();

    //1.同步方法
    @Override
    public  void run() {
        while (true) {
            try {

                lock.lock();//加锁
                if (tockit <= 0) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " 拿到了第" + tockit-- + "张票");
            }finally {
                lock.unlock();//解锁
            }

        }

    }

    public static void main(String[] args) {
        LockTest th = new LockTest();
        new Thread(th, "小明").start();
        new Thread(th, "校长").start();
        new Thread(th, "某某").start();
    }

}
